// transformUtils.js (数据转换处理)
import { countBy, flatten, isEmpty, orderBy } from 'lodash';
import store from '@/store';
export const transformData = (data) => {
  const result = {};
  data.forEach(({ index, item, type }) => {
    const value = type == 'categories' || type == 'features' ? item : index;
    if (!result[type]) result[type] = '';
    result[type] += result[type] ? `,${value}` : value;
  });
  return result;
};
// 转字符串
export const transformToString = (data) => {
  const result = [];
  for (const [key, values] of Object.entries(data)) {
    values.forEach((value) => result.push(`${key}${value}`));
  }
  return result.join(',');
};

// 去重选择的项
export const uniqueSelected = (arr, key) => {
  return Array.from(new Map(arr.map((item) => [item[key], item])).values());
};

// 将嵌套数组扁平化并按 id 计数
export const mapByid = (arr) => countBy(flatten(arr));

// 将下拉选中的code从小到大排序
export const sortByCode = (code) =>
  code
    .slice()
    .sort((a, b) => a - b)
    .join(',');

// 获取最新组合
export const mapBestCombine = (list) =>
  mapByid(list.map((item) => item.bestCombine.split(',')));

// 对 allCombine 的键进行排序
export const sortAllCombineKeys = (allCombine) => {
  return Object.fromEntries(
    Object.entries(allCombine).map(([key, value]) => {
      const sortedKey = key
        .split(',')
        .map(Number)
        .sort((a, b) => a - b)
        .join(',');
      return [sortedKey, value];
    }),
  );
};

// 更新 subjectData 中的 chooseNum 值并排序
export const updateSubjectData = (dataMap, subjectData) => {
  subjectData.forEach((item) => (item.chooseNum = 0));
  if (!isEmpty(dataMap)) {
    Object.keys(dataMap).forEach((key) => {
      subjectData.forEach((item) => {
        if (item.id == key) {
          // 仅当 id 匹配时更新 chooseNum 和 time
          item.chooseNum = dataMap[key];
        }
      });
    });
  }
  return orderBy(subjectData, ['chooseNum', 'id'], ['desc', 'asc']);
};

export const getLableName = {
  1: '物理',
  2: '化学',
  3: '生物',
  4: '历史',
  5: '地理',
  6: '思想政治',
  7: '技术',
};

export const getLableCode = {
  物理: '1',
  化学: '2',
  生物: '3',
  历史: '4',
  地理: '5',
  思想政治: '6',
  技术: '7',
};

// 计算匹配率的逻辑
export const updateMatchRate = (data, sgId, matchRateRef) => {
  if (!data.length) {
    matchRateRef.value = 0;
    return;
  }
  const code = sortByCode(sgId); // 将sgId排序并转为字符串
  const totalPercent = data.reduce((acc, item) => {
    if (item.allCombine && typeof item.allCombine === 'object') {
      const sortedAllCombine = sortAllCombineKeys(item.allCombine);
      acc += sortedAllCombine[code]?.percent || 0;
    }
    return acc;
  }, 0);

  // 更新匹配率，四舍五入取整
  matchRateRef.value = Math.floor(totalPercent / data.length);
};
// 设置store回显
export const setStore = (str, data, type) =>
  type ? store.dispatch(str, data) : store.commit(str, data);
export const codeMp = {
  0: '智能选科',
  1: '自主选科',
  2: '',
  3: '',
};
